<script setup lang="ts">
import { onMounted, ref, watch, toRef } from "vue";
import { message } from "@/utils/message";
import { FormInstance } from "element-plus";
import { addPlatformDevice, PlatformDevice } from "@/api/LabPlatformApi";

import {
  Device,
  listDevices,
  changeOpening,
  ChangeSvDC1000
} from "@/api/deviceApi";
import { ContorDevice } from "@/api/LabInstanceApi";
import { Experiment } from "@/api/LabExperimentApi";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  expData: {
    type: Object as PropType<Experiment>,
    default: () => {}
  },
  controlList: {
    type: Array as PropType<ContorDevice[]>,
    default: () => []
  },
  tempControl: {
    type: Object as PropType<ContorDevice>,
    default: () => {}
  },
  configId: {
    type: String,
    default: ""
  },
  ConfigPercentage: {
    type: Number
  }
});

const autoConfigOptions = [{ id: "11", name: "默认程序" }];

const ruleFormRef = ref<FormInstance>();
const contorDevices = ref<Array<Device>>([]); //设备列表

const formVisible = ref(false);
// const formData = ref<PlatformDevice>({ ext: {} });
const formData = ref<ContorDevice>({
  expId: "",
  deviceId: "",
  name: "",
  autoMode: "false",
  autoConfig: "",
  opening: 0,
  temperature: 0,
  model: ""
});

const emit = defineEmits([
  "update:visible",
  "add-item",
  "update:controlList",
  "update:ConfigPercentage",
  "data-confirm-click",
  "delete-item"
]);
const allDevices = ref({});

const contorChange = value => {
  const temp = allDevices.value.find(item => {
    return item.id === value;
  });
  if (temp) {
    formData.value.model = temp.model;
  }
};

const getAllDeviceData = async () => {
  const result = await listDevices();
  allDevices.value = result.data;
  // console.log("result", result);
  const tempAllContorls = result.data.filter(obj => {
    return obj.model == "Valve" || obj.model == "HnwDC1000";
  });
  // console.log("tempAllContorls", tempAllContorls);

  // const expSensors = props.expData.sensors;
  // const contorls = [];

  // console.log("expSensors", expSensors);

  // for (const item in expSensors) {
  //   const a = tempAllContorls.find(obj => {
  //     return obj.id == expSensors[item].deviceId;
  //   });
  //   if (a) {
  //     contorls.push(a);
  //   }
  // }
  // console.log("contorls", contorls);

  contorDevices.value = tempAllContorls;
};

watch(
  () => props.expData,
  newVal => {
    getAllDeviceData();
    formData.value.expId = props.expData.id;
  }
);

watch(
  () => props.tempControl,
  newVal => {
    if (newVal) {
      formData.value = JSON.parse(JSON.stringify(newVal));
      // if (formData.value.autoMode == "自动") {
      //   formData.value.autoMode = true;
      // } else {
      //   formData.value.autoMode = false;
      // }
    }
  }
);

watch(
  () => props.controlList,
  newVal => {
    for (const item in contorDevices.value) {
      const existingObj = newVal.find(obj => {
        return obj.deviceId === contorDevices.value[item].id;
      });
      if (existingObj) {
        contorDevices.value[item].disabled = true;
      }
    }
  }
);

onMounted(() => {
  getAllDeviceData();
  // formData.value.expId = props.expData.id;
});

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      // if (formData.value.autoMode) {
      //   formData.value.autoMode = "自动";
      // } else {
      //   formData.value.autoMode = "手动";
      // }
      // formData.value.autoMode = "hhhhhh";
      formData.value.name = allDevices.value.find(item => {
        return item.id === formData.value.deviceId;
      }).name;

      const tempControlList = props.controlList;
      console.log("tempControlList", tempControlList);

      const existingObj = tempControlList.find(item => {
        return (
          item.expId === formData.value.expId &&
          item.deviceId === formData.value.deviceId
        );
      });
      console.log("existingObj", existingObj);

      if (existingObj) {
        // 如果存在相同id的对象，更新该对象
        Object.assign(existingObj, JSON.parse(JSON.stringify(formData.value)));
        if (formData.value.model == "HnwDC1000") {
          const res = await ChangeSvDC1000({
            deviceId: formData.value.deviceId,
            val: formData.value.temperature
          });
          if (res.errorCode === 0) {
            message("设置成功", { type: "success" });

            // fectchData();
          } else {
            message(res.message, { type: "error" }); // 显示错误消息
          }
        } else if (formData.value.model == "Valve") {
          const res = await changeOpening({
            deviceId: formData.value.deviceId,
            val: formData.value.opening
          });
          if (res.errorCode === 0) {
            message("设置成功", { type: "success" });
          } else {
            message(res.message, { type: "error" }); // 显示错误消息
          }
        }
        console.log("existingObj", existingObj);
      } else {
        // 如果不存在相同id的对象，将新对象添加到数组中
        tempControlList.push(JSON.parse(JSON.stringify(formData.value)));
        await addPlatformDevice({
          expId: props.configId,
          deviceId: formData.value.deviceId,
          interval: 1
        });
        //更新数据
        if (formData.value.model == "HnwDC1000") {
          const res = await ChangeSvDC1000({
            deviceId: formData.value.deviceId,
            val: formData.value.temperature
          });
          if (res.errorCode === 0) {
            message("设置成功", { type: "success" });

            // fectchData();
          } else {
            message(res.message, { type: "error" }); // 显示错误消息
          }
        } else if (formData.value.model == "Valve") {
          const res = await changeOpening({
            deviceId: formData.value.deviceId,
            val: formData.value.opening
          });
          if (res.errorCode === 0) {
            message("设置成功", { type: "success" });
          } else {
            message(res.message, { type: "error" }); // 显示错误消息
          }
        }

        emit("update:ConfigPercentage", props.ConfigPercentage + 20);
      }

      const existingOption = contorDevices.value.find(obj => {
        return formData.value.deviceId === obj.id;
      }); //禁用该项
      existingOption.disabled = true;

      console.log(
        "tempControlList",
        JSON.parse(JSON.stringify(tempControlList))
      );

      emit("update:controlList", JSON.parse(JSON.stringify(tempControlList)));

      emit("data-confirm-click");
      // message("已修改，请保存", { type: "success" });
      formVisible.value = false;
      resetForm(formEl);
    }
  });
};

const handleClickDelete = async () => {
  closeDialog();
  emit("delete-item", formData.value.deviceId);
};

const closeDialog = () => {
  formVisible.value = false;
  resetForm(ruleFormRef.value);
};

watch(
  () => formVisible.value,
  val => {
    emit("update:visible", val);
  }
);

watch(
  () => props.visible,
  val => {
    formVisible.value = val;
  }
);

watch(
  () => props.data,
  val => {
    formData.value = val;
  }
);

const rules = {
  deviceId: [{ required: true, message: "请选择控制器", trigger: "blur" }]
};
</script>

<template>
  <el-dialog
    v-model="formVisible"
    title="添加控制器"
    :width="680"
    :before-close="closeDialog"
  >
    <!-- {{ expData }}
    <div style="margin: 20px" />
    <div />
    {{ controlList }} -->
    <!-- {{ configId }} -->
    <!-- {{ formData }} -->
    <!-- {{ expData }}
    <div />
    {{ formData }}
    <div />
    {{ allDevices }}
    <div />
    {{ contorDevices }} -->
    <!-- 表单内容 -->
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="控制器" prop="deviceId">
        <el-select
          v-model="formData.deviceId"
          @change="contorChange"
          placeholder="请选择控制器"
        >
          <el-option
            v-for="item in contorDevices"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            :disabled="item.disabled"
          />
        </el-select>
      </el-form-item>

      <template v-if="formData.deviceId">
        <el-form-item :label="formData.autoMode ? '自动模式' : '手动模式'">
          <el-switch v-model="formData.autoMode" inline-prompt />
        </el-form-item>

        <template v-if="!formData.autoMode">
          <el-form-item
            v-if="formData.model == 'Valve'"
            label="目标开度"
            prop="opening"
          >
            <el-input-number
              v-model="formData.opening"
              :min="0"
              :max="100"
              controls-position="right"
            />
            <span style="margin-left: 10px">%</span>
          </el-form-item>
          <el-form-item
            label="目标温度"
            v-if="formData.model == 'HnwDC1000'"
            prop="temperature"
          >
            <el-input-number
              v-model="formData.temperature"
              :min="0"
              :max="200"
              controls-position="right"
            />
            <span style="margin-left: 10px"> ℃</span>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="控制程序">
            <el-select
              v-model="formData.autoConfig"
              placeholder="请选择控制程序"
            >
              <el-option
                v-for="item in autoConfigOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </template>
    </el-form>
    <template #footer>
      <el-button @click="handleClickDelete()" style="margin-right: auto"
        >删除</el-button
      >

      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>
